var dealers = function(){
    var html = '<div style="margin: 10px">\n' +
        '<div style="margin-top: 10px;margin-right: 20px">\n' +
        '    <form class="layui-form" action="javascript:;" id="selectStockForm">\n' +
        '        <div class="layui-form-item">\n' +
        '            <div class="layui-inline">\n' +
        '                <label class="layui-form-label">代理帐号</label>\n' +
        '                <div class="layui-input-inline">\n' +
        '                    <input type="text" name="account" id="account" autocomplete="off" placeholder="请输入代理帐号"\n' +
        '                           class="layui-input">\n' +
        '                </div>\n' +
        '            </div>\n' +
        '        </div>\n' +
        '            <div class="layui-form-item">\n' +
        '                <div class="layui-inline">\n' +
        '                    <div class="layui-input-block">\n' +
        '                        <button class="layui-btn" lay-submit="" lay-filter="demo2">立即搜索</button>\n' +
        '                    </div>\n' +
        '                </div>\n' +
        '            </div>\n' +
        '    </form>\n' +
        '</div>\n' +
        '    <hr style="margin-bottom: 20px">\n' +
        '    <div style="margin-left: 10px;margin-right: 10px">\n' +
        '        <table class="layui-hide" id="demo" lay-filter="test"></table>\n' +
        '    </div>\n' +
        '    <input id="addProductHidden" value="" hidden="hidden">\n' +
        '</div>';
    layui.use(['table', 'form', 'jquery', 'element', 'laydate'], function () {
        var table = layui.table
            , form = layui.form
            , $ = layui.jquery
            , laydate = layui.laydate
            , element = layui.element;

        $("#mainbody").html(html);
        form.render();
        //日期
        laydate.render({
            elem: '#date1'
            , type: 'datetime'
        });
        laydate.render({
            elem: '#date2'
            , type: 'datetime'
        });

        var tableRender = function () {
            //执行一个 table 实例

            table.render({
                elem: '#demo'
                , height: 420
                , id:"adminList"
                , url: 'admin/getList' //数据接口
                , title: '代理列表'
                , page: true //开启分页
                // , toolbar: 'default'
                , limit: 10
                , limits: [10, 20, 30]
                , cols: [[ //表头
                    {type: 'checkbox'}
                    , {field: 'username', align: 'center', title: '用户名', width: 130}
                    // , {field: 'productNumber', align: 'center', title: '产品编号', width: 130, edit: 'text'}
                    , {field: 'name', align: 'center', title: '代理名', width: 130}
                    , {field: 'money', align: 'center', title: '代理余额', width: 130}
                    // , {field: 'productLowerLimit', align: 'center', title: '库存下限', width: 220,edit: 'text'}
                    , {
                        field: 'switch', title: '启用/禁用', align: 'center', width: 90, templet: function (res) {
                            if (res.state == 1) {
                                return '<input value="'+res.id+'" hidden="hidden"><input type="checkbox"  lay-skin="switch" lay-filter=test1 lay-text="ON|OFF">';
                            } else {
                                return '<input value="'+res.id+'" hidden="hidden"><input type="checkbox"  lay-skin="switch" lay-filter=test1 lay-text="ON|OFF" checked>';
                            }
                        }
                    }
                    , {
                        field: 'doSth', title: '操作', width: 200, align: 'center', templet: function (res) {
                            return '<input value="'+res.id+'" hidden="hidden" name="id">' +
                                '<a class="layui-btn layui-btn-primary layui-btn-sm reset" style="background-color: #009688;color:white;" id="reset-dealer">重置密码</a>';
                        }
                    }

                ]]
            });
        }

        //初始化表格
        tableRender();


        var openUpdateProduct = function(json){
            layer.confirm('确定提交编辑吗？', {icon: 3, title:'提示'}, function(index){
                //checkbox选中是的class
                var checked = "layui-unselect layui-form-checkbox layui-form-checked";
                //获得选中的checkbox集合
                var list = $('div[class="'+checked+'"]');
                $.each(list,function(i,item){
                    //获取到当前switch开关的值并赋值给选中的值的对象集合
                    var status =$(this).parents("tr").find('td[data-field="switch"]').find('em').html();
                    if(status=="OFF"){
                        json[i].productStatus=1
                    }else{
                        json[i].productStatus=0
                    }
                });
                $.ajax({
                    type: "POST",
                    url: "/updateProduct",
                    traditional: true,
                    data: JSON.stringify(json),
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        table.reload("productList");
                        layer.msg('编辑成功！', {
                            icon: 1,
                            time: 1000 //2秒关闭（如果不配置，默认是3秒）
                        });
                    },
                    error: function () {
                        console.log("调用编辑方法失败！");
                    }
                });

            });
        }


        var openDeleteProduct = function(json){
            layer.confirm('确定删除勾选数据吗？', {icon: 3, title:'提示'}, function(index){
                var arr = new Array();
                debugger;
                for(var i =0 ;i < json.length;i++){
                    arr.push(json[i].productId);
                }
                $.ajax({
                    type: "POST",
                    url: "/deleteProduct",
                    traditional: true,
                    data: JSON.stringify(arr),
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        table.reload("productList");
                        layer.msg('删除成功！', {
                            icon: 1,
                            time: 1000 //2秒关闭（如果不配置，默认是3秒）
                        });
                    },
                    error: function () {
                        console.log("调用删除方法失败！");
                    }
                });
            });
        }

        //监听头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id)
                ,data = checkStatus.data; //获取选中的数据
            switch(obj.event){
                case 'add':
                    openAddProduct();
                    break;
                case 'update':
                    layer.msg("此按钮暂未开放功能");
                    // var data = checkStatus.data;
                    // if(data.length<1){
                    //     layer.msg('未选择数据！',
                    //         {icon: 2, time: 500}
                    //     )
                    // }else{
                    //     openUpdateProduct(data);
                    // }
                    break;
                case 'delete':
                    var data = checkStatus.data;
                    openDeleteProduct(data);
                    break;
            };
        });





        //监听搜索按钮
        form.on('submit(demo2)', function (data) {
            console.log(data);
            // var begin = $("#date1").val();
            // var end = $("#date2").val();
            table.reload('adminList', {
                // where: {"id":account, "beginStr": begin, "endStr": end,}
                where: {"id":data.field.account}
            });
        });


        form.on('switch(test1)', function (data) {
            var x = data.elem.checked;
            if (x) {
                handleSwitch("确定启用吗？", data, x);
            } else {
                handleSwitch("确定禁用吗？", data, x);
            }
        });

        var handleSwitch = function (content, data, isChecked) {
            var tableDiv = $(data.othis);
            var tableId = tableDiv.parent().find("input").eq(0).val();
            var tableBut = tableDiv.find("em").html();
            var tableButId;
            if (tableBut=="ON"){
                tableButId = 0;
            }
            if (tableBut=="OFF") {
                tableButId = 1;
            }
            var mydata = {
                id: tableId,
                state: tableButId
            };
            var req = JSON.stringify(mydata)
            layer.open({
                content: content
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    $.ajax({
                        url:'/admin/changeStatus',
                        data:req,
                        // dataType:'text',
                        type:'post',
                        contentType: "application/json",
                        success:function (data) {
                            console.log(data);
                            if (data == 'success'){
                                table.reload('adminList');
                            }else{
                                layer.msg('错误');
                            }
                        },
                        error: function (data) {

                            layer.msg(JSON.parse(data.responseText).message,{ icon: 1, time: 1000 });
                        }
                    });
                    data.elem.checked = isChecked;
                    form.render();
                    layer.close(layer.index);
                    //按钮【按钮一】的回调
                }
                , btn2: function (index, layero) {
                    //按钮【按钮二】的回调
                    data.elem.checked = !isChecked;
                    form.render();
                    layer.close(layer.index);
                    //return false 开启该代码可禁止点击该按钮关闭
                }
                , cancel: function () {
                    //右上角关闭回调
                    data.elem.checked = !isChecked;
                    form.render();
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
            return false;
        }
        $(document).on('click', '#reset-dealer', function(data) {
            var dealerId = $(this).parent().find("input").eq(0).val();
            console.log($(this));
            layer.confirm("确定重置密码吗?",{

                    btn: ['确定', '取消']
                    ,title:"提示"
                }, function (index, layero) {
                    $.ajax({
                        type: "POST",
                        url: "admin/reset",
                        traditional: true,
                        // dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(dealerId),
                        success: function (data) {
                            console.log(data);
                            layer.msg("重置成功!",{ icon: 1, time: 1000 });
                            table.reload('adminList');
                        },
                        error: function () {

                            layer.msg(JSON.parse(data.responseText).message,{ icon: 1, time: 1000 });
                        }
                    });
                }
            );
        });

    })
}